package ai.xiaodao.tool;

import ai.xiaodao.config.BrokerConfig;
import ai.xiaodao.config.Const;
import ai.xiaodao.config.DBConfig;
import ai.xiaodao.config.Security;
import com.futu.openapi.pb.Notify;
import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;


public class ConfigUtil {
    static Logger log = Logger.getLogger(BrokerConfig.class.getName());

    public static  void initConfig(String cnfPath) {
        //check the input config file path
        if (null != cnfPath && cnfPath.length() > 0) {
            //initialize database config
            DBConfig.getIns(cnfPath+File.separator+Const.DB_CNF);
            //initialize broker config
            BrokerConfig.getIns(cnfPath+File.separator+Const.BROKER_CNF);
            //initialize security config
            Security.getIns(cnfPath+File.separator+Const.SECURITY_CNF);
        } else {
            log.error("The config path in correct please check");
            System.exit(0);
        }

    }

    public static Properties readProps(String configFile) {
        Properties prop = new Properties();
        log.info("initializing " + configFile);
        try {
            FileInputStream fis = new FileInputStream(configFile);
            prop.load(fis);
            if (prop.size() == 0) {
                log.error(configFile + " load failed");
            } else {
                //todo,and give up at present
//                ClearComments(prop);
                log.info("config file read succeed");
            }

        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
            log.error(configFile + " not found");
            System.exit(1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            log.error(configFile + " read exception");
            System.exit(1);
        }
        return prop;
    }


    /**
     * clear the comments in the config file        q
     *
     * @param initProps
     */
    public static void ClearComments(Properties initProps) {
        Set sets = initProps.keySet();
        Iterator itr = sets.iterator();
        {
            String str = (String) itr.next();
            String val = initProps.getProperty(str);
            val = val.substring(val.indexOf(";"), val.length() - 1);
            log.error(val.indexOf(";") + " " + val.length());
            initProps.setProperty(str, val);
        }

    }
}
